/*
 * @lc app=leetcode.cn id=117 lang=java
 *
 * [117] 填充每个节点的下一个右侧节点指针 II
 */

// @lc code=start
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;


class Solution {
    public Node connect(Node root) {
        if(root==null){
            return root;
        }

        Node res = root;
        Queue<Node> queue = new LinkedList<>();

        queue.offer(root);

        while(!queue.isEmpty()) {

            int size = queue.size();

            while(size > 0) {
                Node tmp = queue.poll();

                if(size != 0) {
                    tmp.next = queue.peek();
                }
                if(tmp.left != null) {
                    queue.offer(tmp.left);
                }
                if(tmp.right != null) {
                    queue.offer(tmp.right);
                }

                size --;
            }
        }
        return res;
        
    }
}
// @lc code=end

